/*
* 苏州海管家物流科技有限公司（https://www.hgj.com/）.
* 苏公网安备32059002003385号 © 2015-2022 Hgj.com All Rights Reserved. | 苏ICP备15030950号.
* @Date: 2022.03.21.
* @Author
* @Description 企点 管理后台 - 数据统计 - 企业信息管理 模块.
**/
<template>
  <Layout>
    <!-- 查询条件 -->
    <section class="p-5 bg-white mb-5">
      <el-form
        ref="queryForm"
        label-width="120px"
        class="flex flex-wrap"
        :model="query"
      >
        <el-form-item
          class="w-4/12"
          label="企业名称"
          prop="corpName"
        >
          <el-input v-model.trim="query.corpName" />
        </el-form-item>

        <el-form-item
          class="w-4/12"
          label="销售区域"
          prop="saleArea"
        >
          <el-select
            v-model.trim="query.saleArea"
            multiple
          >
            <el-option
              v-for="item in saleArea"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item
          class="w-4/12"
          label="销售类型"
          prop="saleType"
        >
          <el-select v-model.trim="query.saleType">
            <el-option
              label="全部"
              :value="null"
            />
            <el-option
              label="分销"
              :value="1"
            />
            <el-option
              label="直销"
              :value="2"
            />
          </el-select>
        </el-form-item>

        <el-form-item
          class="w-4/12"
          label="经销商"
          prop="dealerId"
        >
          <el-select
            v-model.trim="query.dealerId"
            filterable
            remote
            :remote-method="remoteMethod"
          >
            <el-option
              label="全部"
              :value="null"
            />
            <el-option
              v-for="item in distributorList"
              :key="item.id"
              :label="item.dealerName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item
          class="w-4/12"
          label="客户成功"
          prop="customerSuccess"
        >
          <el-select
            v-model.trim="query.customerSuccess"
            filterable
            remote
            :remote-method="remoteMethod"
          >
            <el-option
              label="全部"
              :value="null"
            />
            <el-option
              v-for="item in customerList"
              :key="item.id"
              :label="item.dataCode"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          class="w-4/12"
          label="企业标签"
          prop="tags"
        >
          <el-select
            v-model.trim="query.tags"
            multiple
          >
            <el-option
              v-for="item in queryLabel"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            @click="() => handleQueryClick({ num: 1 })"
          >
            查询
          </el-button>
          <el-button
            class="mr10"
            @click="handleReset"
          >
            重置
          </el-button>

          <el-dropdown @command="handleExport">
            <el-button
              type="primary"
              :disabled="loading"
            >
              导出
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="company">
                导出企业列表
              </el-dropdown-item>
              <el-dropdown-item command="detail">
                导出企业及下属账号列表
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </el-form-item>
      </el-form>
    </section>
    <!-- 列表 -->
    <section>
      <el-table
        ref="table"
        :data="corpData"
        border
        row-key="id"
        @expand-change="getDetail"
      >
        <el-table-column
          fixed="left"
          type="expand"
        >
          <!-- 二级 table 查询条件 -->
          <template #default="props">
            <div class="flex search-line">
              <div class="flex">
                <div class="ex-label">
                  账号名:
                </div>
                <el-input
                  v-model="props.row.name"
                  class="ex-input"
                />
              </div>
              <div class="flex">
                <div class="ex-label">
                  手机号:
                </div>
                <el-input
                  v-model="props.row.mobile"
                  class="ex-input"
                />
              </div>

              <div class="flex">
                <el-button
                  type="primary"
                  @click="() => handleChildSearch(props.row)"
                >
                  查询
                </el-button>
                <el-button @click="handleChildReset(props.row)">
                  重置
                </el-button>
              </div>
            </div>

            <el-table
              :data="props.row.detailRow"
              style="width: 100%"
            >
              <el-table-column
                prop="name"
                width="140"
                label="账号名"
              />
              <el-table-column
                width="60px"
                label="头像"
              >
                <template #default="{ row }">
                  <el-image :src="row.face" />
                </template>
              </el-table-column>

              <el-table-column
                width="60px"
                label="状态"
              >
                <template #default="{ row }">
                  <span v-if="row.active == 2">正常</span>
                  <span v-else>停用</span>
                </template>
              </el-table-column>

              <el-table-column
                prop="openId"
                label="OpenId"
                width="180"
              />
              <el-table-column
                prop="mobile"
                label="手机号"
                width="120"
              />
              <el-table-column label="现舱商机">
                <template #default="{ row }">
                  <div
                    v-for="(m, n) in row.cabinHarbourList.split(',')"
                    :key="n"
                  >
                    {{ m }}
                  </div>
                </template>
              </el-table-column>

              <el-table-column label="关键词">
                <template #default="{ row }">
                  <el-popover
                    placement="top-start"
                    width="200"
                    trigger="hover"
                  >
                    <div>{{ row.keyWords }}</div>
                    <div slot="reference">
                      {{ row.keyWords }}
                    </div>
                  </el-popover>
                </template>
              </el-table-column>

              <el-table-column
                prop="createdAt"
                label="创建时间"
                width="180"
              />
              <el-table-column
                prop="expireTime"
                label="过期时间"
                width="180"
              />

              <el-table-column
                label="超续费"
                width="70"
              >
                <template #default="{ row }">
                  <span v-if="row.timeout">是</span>
                  <span v-else>否</span>
                </template>
              </el-table-column>

              <el-table-column
                width="100px"
                label="关键词设置"
              >
                <template #default="{ row }">
                  <el-switch
                    v-model="row.enableCabinFlag"
                    :active-value="1"
                    :inactive-value="0"
                    @change="(val) => { handleSetCabin(val, row, props.row )}"
                  />
                </template>
              </el-table-column>
              <el-table-column
                width="80px"
                label="权限设置"
              >
                <template #default="{ row }">
                  <el-switch
                    v-model="row.appSwitchFlag"
                    :active-value="1"
                    :inactive-value="0"
                    @change="(val) => {handleSetAuth( val, row, props.row )}"
                  />
                </template>
              </el-table-column>
            </el-table>

            <div class="text-center py-4">
              <el-pagination
                v-model:current-page="props.row.detailNum"
                background
                :page-size="detailSize"
                :total="props.row.detailTotal"
                @current-change="
                  (val) => { handleChangeDetailPage(val, props.row)}"
              />
            </div>
          </template>
        </el-table-column>
        <!-- 一级 list -->
        <el-table-column
          label="企业ID"
          prop="corpId"
          width="140"
        />
        <el-table-column
          label="企业名称"
          prop="corpName"
          width="180"
        />
        <el-table-column
          label="销售区域"
          prop="saleAreaName"
          width="180"
        />
        <el-table-column
          label="销售类型"
          prop="saleTypeName"
          width="180"
        />
        <el-table-column
          label="经销商"
          prop="dealer"
          width="180"
        />
        <el-table-column
          label="客户成功"
          prop="customerSuccess"
          width="180"
        />
        <el-table-column
          label="标签"
          prop="companyTagsDetail"
          width="180"
        />
        <el-table-column
          label="备注"
          prop="remark"
          width="180"
        />

        <el-table-column
          label="操作"
          width="140"
        >
          <template #default="{ row }">
            <el-button
              type="text"
              @click="handleEditClick(row)"
            >
              编辑
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="text-center py-4">
        <el-pagination
          v-model:current-page="query.num"
          background
          :total="data.total"
          @current-change="getList"
        />
      </div>
    </section>
    <!-- 编辑企业信息 弹窗 -->
    <el-dialog
      v-model:visible="editDialogVisible"
      title="编辑企业信息"
      width="440px"
    >
      <el-form
        ref="form"
        :model="form"
        label-width="80px"
      >
        <el-form-item label="企业ID">
          <el-input
            v-model="form.corpId"
            disabled
          />
        </el-form-item>

        <el-form-item label="企业名称">
          <el-input
            v-model="form.corpName"
            disabled
          />
        </el-form-item>

        <el-form-item label="销售区域">
          <el-select
            v-model="form.saleArea"
            placeholder="请选销售区域"
          >
            <el-option
              v-for="item in saleArea"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="销售类型">
          <el-radio
            v-model="form.saleType"
            :label="1"
          >
            分销
          </el-radio>
          <el-radio
            v-model="form.saleType"
            :label="2"
          >
            直销
          </el-radio>
        </el-form-item>

        <el-form-item label="经销商">
          <el-select
            v-model.trim="form.dealerId"
            @change="handleDealerChange"
          >
            <el-option
              v-for="item in distributorList"
              :key="item.id"
              :label="item.dealerName"
              :value="item.dealerId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="客户成功">
          <el-select v-model.trim="form.customerSuccessId">
            <el-option
              v-for="item in customerList"
              :key="item.id"
              :label="item.dataCode"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="企业标签">
          <div class="flex tags-wrapper">
            <div
              v-for="(item, index) in form.companyTags"
              :key="item"
            >
              <el-tag
                class="label-list"
                type="info"
                effect="plain"
                :closable="true"
                @close="clickClose(index)"
              >
                {{ item }}
              </el-tag>
            </div>
          </div>
          <!-- 添加 标签 弹窗 -->
          <el-tag
            class="tag add-tag cursor-pointer"
            type="info"
            effect="plain"
            @click="handleClickEditTags"
          >
            <i class="el-icon-plus" />
          </el-tag>
        </el-form-item>


        <el-form-item label="备注">
          <el-input
            v-model="form.remark"
            resize="none"
            type="textarea"
            maxlength="100"
            show-word-limit
          />
        </el-form-item>
      </el-form>

      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="handleSaveClick"
        >保 存</el-button>
      </span>
    </el-dialog>

    <!-- 标签新增、编辑 -->
    <EditTags
      ref="EditTags"
      @ok="handleTagOk"
    />
  </Layout>
</template>

<script>
import dayjs from 'dayjs'
import { mapGetters } from 'vuex'
import EditTags from './edit-tags'
import Layout from '@/layout/index.vue'
import { employeeList, setAuth, setCabin } from '@/api/company'
import {
    getCorpPage,
    customerSucList,
    getUserTags,
    getDealer,
    saveChanges,
    companyExport,
    companyDetailExport
} from '@/api/records'


export default {
    components: {
        Layout,
        EditTags
    },
    data() {
        return {
            loading: false,
            corpData: [],
            query: { // 查询条件
                num: 1,
                size: 10,
                tags: [], // 标签
                corpName: '', // 企业名称
                dealerId: null, // 经销商ID
                saleArea: null, // 销售区域
                saleType: null, // 销售类型
                customerSuccess: '' // 客户成功
            },
            form: { // 编辑参数
                id: '', // 公司信息ID
                corpId: '', // 公司ID
                dealer: '', // 经销商
                remark: '', // 备注
                corpName: '', // 公司名称
                dealerId: '', // 经销商ID
                saleArea: '', // 销售区域
                saleType: 1, // 销售类型
                companyTags: [], // 企业标签
                customerSuccess: '', // 客户成功
                customerSuccessId: ''
            },
            saleArea: [{ // 销售区域
                value: 1,
                label: '华东'
            }, {
                value: 2,
                label: '华南'
            }, {
                value: 3,
                label: '华北'
            }, {
                value: 4,
                label: '其余'
            }],
            detailSize: 5,
            queryLabel: [], // 全部标签 - 查询条件
            customerList: [], // 客户成功 数据
            distributorList: [], // 经销商列表
            editDialogVisible: false // 标签编辑 弹窗
        }
    },
    computed: {
        ...mapGetters({
            data: 'company/data',
            dict: 'dict/all'
        })
    },

    created() {
        this.getList() // 查询公司列表
        this.getLabel()
        this.getDistributor() // 获取经销商信息
        this.getCustomerSuccess() // 客户成功 数据
    },
    methods: {
        /**
        *@Description 查询 数据查询.
        *@Return .
       **/
        getList() {
            getCorpPage(this.query).then(res => {
                this.corpData = res.data.records.map(item => {
                    item.detailRow = []
                    item.name = ''
                    item.mobile = ''
                    return item
                })
            })
        },
        /**
        *@Description 查询所有标签.
        *@Return .
       **/
        getLabel() {
            getUserTags().then(res => {
                this.queryLabel = [...res.data]
            })
        },
        /**
        *@Description 获取客户成功 数据.
        *@Return .
       **/
        getCustomerSuccess() {
            customerSucList({code: 1005}).then(res => {
                this.customerList = [...res.data]
            })
        },
        /**
        *@Description 获取 经销商 列表 数据.
        *@Return .
       **/
        getDistributor() {
            getDealer().then(res => {
                if (res?.data) {
                    this.distributorList = res.data.map(item => {
                        item.dealerId = item.id
                        return item
                    })
                }
            })
        },
        /**
        *@Description 查询 按钮.
        *@Return .
       **/
        handleQueryClick(query = {}) {
            this.query = { ...this.query, ...query }
            this.getList()
        },
        /**
       *@Description 企业信息管理-导出.
       *@Return .
       **/
        async handleExport(type) {
            const params = { ...this.query }
            try {
                let res = null
                this.loading = true
                let name = '企业列表'

                if (type === 'company') {
                    name = '企业列表'
                    res = await companyExport(params)
                } else {
                    name = '企业及下属账号列表'
                    res = await companyDetailExport(params)
                }

                const url = window.URL.createObjectURL(
                    new Blob([res], {
                        type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
                    })
                )
                const link = document.createElement('a')
                link.style.display = 'none'
                link.href = url
                link.setAttribute('download', `${name}_${dayjs().format('YYYY-MM-DD_HH_mm_ss')}.xlsx`)
                document.body.appendChild(link)
                link.click()
                document.body.removeChild(link)
            } catch (e) {
                console.log('导出异常：', e)
            } finally {
                this.loading = false
            }
        },
        /**
        *@Description 编辑 事件.
        *@Return .
       **/
        async handleEditClick(row) {
            this.$refs.EditTags.corpId = row.corpId
            this.editDialogVisible = true
            this.form = {...row}

        },
        /**
        *@Description 编辑弹窗 经销商选择事件.
        *@Return .
       **/
        handleDealerChange(e) {
            this.form.dealerId = e
            this.form.dealer = this.distributorList.filter(item => item.id === e)[0].dealerName

        },
        /**
        *@Description 监听 table 点击当前行.
        *@Return .
       **/
        async getDetail(row, rows) {
            const arr = rows.filter((item) => item.id === row.id)
            if (!arr.length) return
            let res = await this.searchDetail(row)

            row.name = ''
            row.mobile = ''
            row.detailRow = res.data.records
            row.detailTotal = res.data.total
        },
        /**
        *@Description 根据id 查询 详情.
        *@Return .
       **/
        async searchDetail(row) {
            const params = {
                name: row.name,
                num: row.detailNum,
                mobile: row.mobile,
                corpId: row.corpId,
                size: this.detailSize
            }
            return await employeeList({ ...params })
        },
        /**
        *@Description 编辑 修改 - 保存 按钮事件.
        *@Return .
       **/
        handleSaveClick() {
            this.form.customerSuccess = this.form.customerSuccessId
            saveChanges({...this.form}).then(() => {
                this.$message.success('修改成功！')
                this.editDialogVisible = false
                this.getList()
            })
        },
        /**
        *@Description 企业标签 - 本地删除事件.
        *@Return .
       **/
        clickClose(index) {
            this.form.companyTags.splice(index, 1)
        },
        handleClickEditTags() {
            this.$refs.EditTags.showDialog(this.form.companyTags)
        },
        /**
        *@Description 监听 标签 确定回调事件.
        *@Return .
       **/
        handleTagOk(item) {
            this.form.companyTags = [...item]
        },
        /**
        *@Description 经销商 数据查询.
        *@Return .
       **/
        remoteMethod(query) {
            if (query !== '') {
                this.loading = true
                setTimeout(() => {
                    this.loading = false
                    this.options = this.list.filter(item => {
                        return item.label.toLowerCase()
                            .indexOf(query.toLowerCase()) > -1
                    })
                }, 200)
            } else {
                this.options = []
            }
        },
        async handleSetCabin(val, row) {
            let res = await setCabin({ id: row.id, status: val })
            if (res.data) {
                this.$message.success('设置成功')
            } else this.$message.error('设置失败')
        },
        tableMounted() {
            let dom = this.$el.querySelectorAll('.table-item')
            if (dom.length === 2) {
                dom[1].remove()
            }
        },

        async handleSetAuth(val, row, tableRow) {
            let res = await setAuth({
                flag: val,
                id: row.id,
                openId: row.openId
            })
            if (res.data) {
                this.$message.success('设置成功')
                if (val) {
                    tableRow.enableAppTotal++
                } else {
                    tableRow.enableAppTotal--
                }
            } else this.$message.error('设置失败')
        },


        async handleChangeDetailPage(val, row) {
            let res = await this.searchDetail(row)
            row.detailRow = res.data.records
            row.detailTotal = res.data.total
        },

        handleReset() {
            this.$refs.queryForm.resetFields()
            this.query.num = 1
            this.getList()
        },
        /**
        *@Description 公司 列表 子集 信息 查询 - 重置.
        *@Return .
       **/
        async handleChildSearch(row) {
            let res = await this.searchDetail(row)
            row.detailRow = res.data.records
            row.detailTotal = res.data.total
        },
        handleChildReset(row) {
            row.name = ''
            row.mobile = ''
        }
    }
}
</script>
<style lang="scss" scoped>
.mr10 {
  margin-right: 10px;
}
.search-line {
    margin-bottom: 15px;
}
.ex-label {
    width: 50px;
    text-align: right;
    margin-right: 10px;
    line-height: 36px;
}
.ex-input {
    width: 200px;
    margin-right: 20px;
}
/* 标签 */
.add-tag {
  width: 50px;
  text-align: center;
}

.tag {
  margin: 0 10px 10px 0;
  cursor: pointer;
  &:hover {
     color: #006aff;
     border-color: #006aff;
   }
}

.tags-wrapper {
  flex-wrap: wrap;
}
.label-list {
  margin: 0 10px 10px 0;
}
</style>

